/**
 * 与用户相关的一系列函数，负责与数据库交互
 */
const { execSql } = require('../db/mysql')

// 注册用户
const signup = async (userInfo) => {
  let sql, result
  try {
    sql = 'select username from users where username = ?'
    result = await execSql(sql, [userInfo.username])
    // 如果用户已存在
    if (result.length > 0) {
      return false
    }
    // 如果用户不存在，在创建新用户
    sql = 'insert into users set ?'
    result = await execSql(sql, userInfo)
    return result
  } catch (error) {
    console.log(error)
  }
}

// 登录
const login = async (userInfo) => {
  let sql = 'select * from users where username = ? and password = ?'
  try {
    const result = await execSql(sql, [userInfo.username, userInfo.password])
    return result[0]
  } catch (error) {
    console.log(error)
  }
}

// 获取用户点赞过的留言
const getUserLikes = async (username) => {
  let sql = 'select message_id from likes where username = ?'
  try {
    const results = await execSql(sql, [username])
    return results
  } catch (error) {
    console.log(error)
  }
}

// 修改头像
const changeAvatar = async (userInfo) => {
  let sql = 'update users set avatar = ? where username = ?'
  try {
    const result = await execSql(sql, [userInfo.avatar, userInfo.username])
    if (result.affectedRows > 0) {
      return true
    } else {
      return false
    }
  } catch (error) {
    console.log(error)
  }
}

// 修改用户名
const changeUsername = async (userInfo) => {
  let sql, result
  try {
    sql = 'select username from users where username = ?'
    result = await execSql(sql, [userInfo.newUsername])
    // 如果用户名已存在
    if (result.length > 0) {
      return false
    }
    // 如果用户名不存在，则更新用户名
    sql = 'update users set username = ? where username = ?'
    await execSql(sql, [userInfo.newUsername, userInfo.oldUsername])
    result = await execSql(
      'select * from users where username = ?',
      [userInfo.newUsername]
    )
    return result[0]
  } catch (error) {
    console.log(error)
  }
}

module.exports = {
  signup,
  login,
  getUserLikes,
  changeAvatar,
  changeUsername
}
